package com.example.jinyongjie.test_opengles.util;
import static android.opengl.GLES20.*;
/**
 * Created by jinyongjie on 17/3/9.
 */
public class ShaderHelper {
    public static int compileVertexShader(String code)
    {
        return compileShader(GL_VERTEX_SHADER,code);
    }
    public static int compileFragShader(String code)
    {
        return compileShader(GL_FRAGMENT_SHADER,code);
    }

    public static int compileShader(int type,String code)
    {
        final int shaderObjectId = glCreateShader(type);
        if(shaderObjectId == 0)
        {
            return 0;
        }
        glShaderSource(shaderObjectId,code);
        glCompileShader(shaderObjectId);
        final int [] compileStatus = new int[1];
        glGetShaderiv(shaderObjectId,GL_COMPILE_STATUS,compileStatus,0);
        if(compileStatus[0] == 0)
        {
            glDeleteShader(shaderObjectId);
            return 0;
        }
        return shaderObjectId;
    }

    public static int linkProgram(int vertexShaderId,int fragmentShaderId)
    {
        final int programObjectId = glCreateProgram();
        if(programObjectId == 0)
            return 0;
        glAttachShader(programObjectId,vertexShaderId);
        glAttachShader(programObjectId, fragmentShaderId);
        glLinkProgram(programObjectId);
        final int[] linkStatus = new int[1];
        glGetProgramiv(programObjectId, GL_LINK_STATUS, linkStatus, 0);
        if(linkStatus[0] == 0)
        {
            glDeleteProgram(programObjectId);
        }
        return programObjectId;
    }
    public static int buildProgram(String vertexShaderSource,String fragmentShaderSource)
    {
        int vertexShader = ShaderHelper.compileVertexShader(vertexShaderSource);
        int fragShader = ShaderHelper.compileFragShader(fragmentShaderSource);
        return ShaderHelper.linkProgram(vertexShader, fragShader);
    }
}
